/**
 * 认证管理模块
 * 处理用户登录状态、Token管理和权限验证
 */
class AuthManager {
    constructor() {
        this.tokenKey = 'wechat_auth_token';
        this.userInfoKey = 'wechat_user_info';
        this.tokenExpiryKey = 'wechat_token_expiry';
        this.refreshTokenKey = 'wechat_refresh_token';
        
        this.token = null;
        this.userInfo = null;
        this.refreshToken = null;
        this.tokenExpiry = null;
        
        this.init();
    }

    init() {
        this.loadFromStorage();
        this.setupTokenRefresh();
    }

    /**
     * 从localStorage加载认证信息
     */
    loadFromStorage() {
        try {
            this.token = localStorage.getItem(this.tokenKey);
            this.userInfo = localStorage.getItem(this.userInfoKey) ? 
                JSON.parse(localStorage.getItem(this.userInfoKey)) : null;
            this.refreshToken = localStorage.getItem(this.refreshTokenKey);
            this.tokenExpiry = localStorage.getItem(this.tokenExpiryKey) ? 
                parseInt(localStorage.getItem(this.tokenExpiryKey)) : null;
        } catch (error) {
            console.error('加载认证信息失败:', error);
            this.clearAuth();
        }
    }

    /**
     * 保存认证信息到localStorage
     */
    saveToStorage() {
        try {
            if (this.token) {
                localStorage.setItem(this.tokenKey, this.token);
            }
            if (this.userInfo) {
                localStorage.setItem(this.userInfoKey, JSON.stringify(this.userInfo));
            }
            if (this.refreshToken) {
                localStorage.setItem(this.refreshTokenKey, this.refreshToken);
            }
            if (this.tokenExpiry) {
                localStorage.setItem(this.tokenExpiryKey, this.tokenExpiry.toString());
            }
        } catch (error) {
            console.error('保存认证信息失败:', error);
        }
    }

    /**
     * 生成JWT Token (简化版本)
     */
    generateToken(userData) {
        const header = {
            alg: 'HS256',
            typ: 'JWT'
        };

        const payload = {
            sub: userData.muserid || userData.openid || 'unknown',
            name: userData.name || '',
            company: userData.company || '',
            buserid: userData.buserid || '',
            flag: userData.flag || '',
            iat: Math.floor(Date.now() / 1000),
            exp: Math.floor(Date.now() / 1000) + (24 * 60 * 60), // 24小时过期
            jti: this.generateRandomId()
        };

        const encodedHeader = btoa(JSON.stringify(header));
        const encodedPayload = btoa(JSON.stringify(payload));
        const signature = this.generateSignature(encodedHeader, encodedPayload);

        return `${encodedHeader}.${encodedPayload}.${signature}`;
    }

    /**
     * 生成签名 (简化版本)
     */
    generateSignature(encodedHeader, encodedPayload) {
        const secret = 'your-secret-key-change-in-production';
        const data = `${encodedHeader}.${encodedPayload}`;
        
        // 简化的签名算法，生产环境应使用更安全的方式
        let hash = 0;
        for (let i = 0; i < data.length; i++) {
            const char = data.charCodeAt(i);
            hash = ((hash << 5) - hash) + char;
            hash = hash & hash; // 转换为32位整数
        }
        
        return Math.abs(hash).toString(36);
    }

    /**
     * 生成随机ID
     */
    generateRandomId() {
        return Math.random().toString(36).substr(2, 9);
    }

    /**
     * 验证Token有效性
     */
    validateToken(token) {
        if (!token) return false;

        try {
            const parts = token.split('.');
            if (parts.length !== 3) return false;

            const payload = JSON.parse(atob(parts[1]));
            const now = Math.floor(Date.now() / 1000);

            // 检查过期时间
            if (payload.exp && payload.exp < now) {
                return false;
            }

            return true;
        } catch (error) {
            console.error('Token验证失败:', error);
            return false;
        }
    }

    /**
     * 解码Token获取用户信息
     */
    decodeToken(token) {
        if (!token) return null;

        try {
            const parts = token.split('.');
            if (parts.length !== 3) return null;

            return JSON.parse(atob(parts[1]));
        } catch (error) {
            console.error('Token解码失败:', error);
            return null;
        }
    }

    /**
     * 设置认证信息
     */
    setAuth(userData) {
        // 生成新的token
        this.token = this.generateToken(userData);
        this.userInfo = userData;
        this.tokenExpiry = Math.floor(Date.now() / 1000) + (24 * 60 * 60);
        this.refreshToken = this.generateRandomId();

        // 保存到localStorage
        this.saveToStorage();

        // 触发认证状态变更事件
        this.emitAuthChange('login', userData);
    }

    /**
     * 清除认证信息
     */
    clearAuth() {
        this.token = null;
        this.userInfo = null;
        this.refreshToken = null;
        this.tokenExpiry = null;

        // 清除localStorage
        localStorage.removeItem(this.tokenKey);
        localStorage.removeItem(this.userInfoKey);
        localStorage.removeItem(this.tokenExpiryKey);
        localStorage.removeItem(this.refreshTokenKey);

        // 触发认证状态变更事件
        this.emitAuthChange('logout');
    }

    /**
     * 检查是否已登录
     */
    isLoggedIn() {
        if (!this.token) return false;
        return this.validateToken(this.token);
    }

    /**
     * 获取当前用户信息
     */
    getUserInfo() {
        if (!this.isLoggedIn()) return null;
        return this.userInfo;
    }

    /**
     * 获取当前Token
     */
    getToken() {
        if (!this.isLoggedIn()) return null;
        return this.token;
    }

    /**
     * 刷新Token
     */
    async refreshToken() {
        if (!this.refreshToken) return false;

        try {
            // 这里应该调用后端API刷新token
            // 暂时使用前端模拟刷新
            const userData = this.getUserInfo();
            if (userData) {
                this.token = this.generateToken(userData);
                this.tokenExpiry = Math.floor(Date.now() / 1000) + (24 * 60 * 60);
                this.saveToStorage();
                return true;
            }
            return false;
        } catch (error) {
            console.error('Token刷新失败:', error);
            this.clearAuth();
            return false;
        }
    }

    /**
     * 设置Token刷新定时器
     */
    setupTokenRefresh() {
        // 每30分钟检查一次token是否需要刷新
        setInterval(() => {
            if (this.isLoggedIn()) {
                const now = Math.floor(Date.now() / 1000);
                const timeUntilExpiry = this.tokenExpiry - now;
                
                // 如果token在1小时内过期，则刷新
                if (timeUntilExpiry < 3600) {
                    this.refreshToken();
                }
            }
        }, 30 * 60 * 1000); // 30分钟
    }

    /**
     * 检查页面访问权限
     */
    checkPageAccess(requiredAuth = false) {
        if (!requiredAuth) {
            return { allowed: true, reason: 'public_access' };
        }

        if (this.isLoggedIn()) {
            return { allowed: true, reason: 'authenticated' };
        }

        return { allowed: false, reason: 'not_authenticated' };
    }

    /**
     * 处理需要认证的页面访问
     */
    requireAuth(redirectUrl = null) {
        const access = this.checkPageAccess(true);
        
        if (!access.allowed) {
            // 记录当前页面URL，登录后跳转回来
            if (window.location.pathname !== '/index.html' && window.location.pathname !== '/') {
                const returnUrl = encodeURIComponent(window.location.href);
                const loginUrl = `index.html?redirect=${returnUrl}`;
                window.location.href = loginUrl;
            } else {
                window.location.href = 'index.html';
            }
            return false;
        }

        return true;
    }

    /**
     * 处理URL参数登录
     */
    handleUrlLogin() {
        const urlParams = new URLSearchParams(window.location.search);
        const muserid = urlParams.get('muserid');
        const buserid = urlParams.get('buserid');
        const flag = urlParams.get('flag');
        const name = urlParams.get('name');
        const company = urlParams.get('company');

        // 如果有用户信息参数，尝试自动登录
        if (muserid && (flag === 'Y' || !this.isLoggedIn())) {
            const userData = {
                muserid: muserid,
                buserid: buserid || '',
                flag: flag || '',
                name: name || '',
                company: company || ''
            };

            this.setAuth(userData);
            
            // 处理重定向
            const redirect = urlParams.get('redirect');
            if (redirect) {
                window.location.href = decodeURIComponent(redirect);
            }
            
            return true;
        }

        return false;
    }

    /**
     * 触发认证状态变更事件
     */
    emitAuthChange(event, data = null) {
        // 派发自定义事件
        const authEvent = new CustomEvent('authChange', {
            detail: { event, data }
        });
        document.dispatchEvent(authEvent);

        // 调用回调函数
        if (this.authCallbacks && this.authCallbacks[event]) {
            this.authCallbacks[event].forEach(callback => callback(data));
        }
    }

    /**
     * 监听认证状态变更
     */
    onAuthChange(event, callback) {
        if (!this.authCallbacks) {
            this.authCallbacks = {};
        }
        if (!this.authCallbacks[event]) {
            this.authCallbacks[event] = [];
        }
        this.authCallbacks[event].push(callback);
    }

    /**
     * 移除认证状态监听
     */
    offAuthChange(event, callback) {
        if (this.authCallbacks && this.authCallbacks[event]) {
            const index = this.authCallbacks[event].indexOf(callback);
            if (index > -1) {
                this.authCallbacks[event].splice(index, 1);
            }
        }
    }

    /**
     * 获取认证头信息
     */
    getAuthHeaders() {
        const token = this.getToken();
        return token ? { 'Authorization': `Bearer ${token}` } : {};
    }

    /**
     * 检查Token是否即将过期
     */
    isTokenExpiringSoon(withinMinutes = 60) {
        if (!this.tokenExpiry) return false;
        
        const now = Math.floor(Date.now() / 1000);
        const timeUntilExpiry = this.tokenExpiry - now;
        
        return timeUntilExpiry < (withinMinutes * 60);
    }

    /**
     * 获取Token剩余有效期（分钟）
     */
    getTokenTimeRemaining() {
        if (!this.tokenExpiry) return 0;
        
        const now = Math.floor(Date.now() / 1000);
        const timeUntilExpiry = this.tokenExpiry - now;
        
        return Math.max(0, Math.floor(timeUntilExpiry / 60));
    }
}

// 创建全局实例
window.authManager = new AuthManager();

// 页面加载时处理URL登录
document.addEventListener('DOMContentLoaded', () => {
    window.authManager.handleUrlLogin();
});